<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" tip_dom="width=device-width, initial-scale=1.0">
  <title>视频链接缓存</title>
</head>

<body>
  <div>
    
  </div>
  <video width="500px" height="500px" id="video" autoplay controls />
</body>
<script type="text/javascript">
  const video = document.getElementById('video');
  const mediaSource = new MediaSource()
  video.src = URL.createObjectURL(mediaSource)

  // const mimeType = 'video/mp4; codecs="avc1.42E01E"';
  const mimeType = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"';
  // const mimeType = 'video/mp4';

  if (!MediaSource.isTypeSupported(mimeType)) {
    throw 'MIME type not supported:' + mimeType
  }

  mediaSource.addEventListener('sourceclose', (event) => {
    console.warn('mediaSource sourceclose', event);
  });

  mediaSource.addEventListener('sourceended', () => {
    console.log('MediaSource has ended.');
  })

  mediaSource.addEventListener('error', (event) => {
    console.log('mediaSource error', event);
  })

  mediaSource.addEventListener('sourceopen', async () => {
    console.log('MediaSource is open');
    var sourceBuffer
    try {
      sourceBuffer = mediaSource.addSourceBuffer(mimeType);
    } catch (e) {
      return console.error('Failed to add SourceBuffer:', e);
    }

    sourceBuffer.addEventListener('updateend', () => {
      console.log('SourceBuffer update completed.');
    });

    try {
      const response = await fetch('./770kb_tran.mp4');

      const reader = response.body.getReader();
      let done = false;

      while (!done) {
        const { value, done: readerDone } = await reader.read();
        console.log({value, done: readerDone})
        done = readerDone;
        if (!value) {  continue }
        await new Promise((resolve) => {
          if (sourceBuffer.updating) {
            sourceBuffer.addEventListener('updateend', resolve, { once: true });
          } else {
            sourceBuffer.appendBuffer(value);
            resolve();
          }
        });
      }
      console.log('All data appended');
      // 确保所有更新完成后调用 endOfStream
      await new Promise((resolve) => {
        if (!sourceBuffer.updating) {
          resolve();
        } else {
          sourceBuffer.addEventListener('updateend', resolve, { once: true });
        }
      });

      setTimeout(() => {
        video.play();
      }, 2000)

    } catch (error) {
      console.error('Error fetching video:', error);
    }
  });


</script>

</html>